package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 股票主板Controller
 *
 * @author ruoyi
 * @date 2024-12-30
 */
@Controller
@RequestMapping("/system/main/board/four")
public class StockMainBoardFourController extends BaseController {
    private String prefix = "system/main/four";

    @Autowired
    private IStockMainBoardService stockMainBoardService;
    @Autowired
    private IStockMainBoardCustomService stockMainBoardCustomService;
    @Autowired
    private IStockMainBoardDetailService stockMainBoardDetailService;
    @Autowired
    private ISysDictDataService dictDataService;


    private static final int THREAD_COUNT = 11; // 定义线程数量
    private static final int BATCH_SIZE = 300; // 每批次处理的参数数量


    @GetMapping()
    public String board() {
        return prefix + "/board";
    }


    /**
     * 新增股票主板
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存股票主板
     */
    @Log(title = "股票主板", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(StockMainBoard stockMainBoard) {
        return toAjax(stockMainBoardService.insertStockMainBoard(stockMainBoard));
    }

    /**
     * 修改股票主板
     */
    @GetMapping("/edit/{mainId}")
    public String edit(@PathVariable("mainId") Long mainId, ModelMap mmap) {
        StockMainBoard stockMainBoard = stockMainBoardService.selectStockMainBoardByMainId(mainId);
        mmap.put("stockMainBoard", stockMainBoard);
        return prefix + "/edit";
    }

    /**
     * 修改保存股票主板
     */
    @Log(title = "股票主板", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(StockMainBoard stockMainBoard) {
        return toAjax(stockMainBoardService.updateStockMainBoard(stockMainBoard));
    }


    /**
     * 主板股票详细列表
     */

    @PostMapping("/allStockMainBoardDetail")
    @ResponseBody
    public List<StockMainBoardAndDetail> getAllStockMainBoardDetail(MultipartHttpServletRequest request) {
        String mainId = request.getParameter("mainId");
        StockMainBoardDetail stockMainBoardDetail = new StockMainBoardDetail();
        stockMainBoardDetail.setMainId(Long.valueOf(mainId));
        StockMainBoard mainBoard = stockMainBoardService.selectStockMainBoardByMainId(Long.valueOf(mainId));
        List<StockMainBoardDetail> stockMainBoardDetails = stockMainBoardDetailService.selectStockMainBoardDetailList(stockMainBoardDetail);
        List<StockMainBoardAndDetail> stockMainBoardAndDetailList = stockMainBoardDetails.stream().map(person -> {
            StockMainBoardAndDetail stockMainBoardAndDetail = new StockMainBoardAndDetail();
            stockMainBoardAndDetail.setStockName(mainBoard.getStockName());
            stockMainBoardAndDetail.setStockPrice(person.getLastPx());
            stockMainBoardAndDetail.setDay(person.getDay());
            return stockMainBoardAndDetail;
        }).collect(Collectors.toList());
        return stockMainBoardAndDetailList;
    }

    /**
     * 导出股票主板列表
     */

    @Log(title = "股票主板", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(StockMainBoard stockMainBoard) {
        List<StockMainBoard> list = stockMainBoardService.selectStockMainBoardList(stockMainBoard);
        ExcelUtil<StockMainBoard> util = new ExcelUtil<StockMainBoard>(StockMainBoard.class);
        return util.exportExcel(list, "股票主板数据");
    }


    /**
     * 根据主板id查询股票详细
     */

//    @GetMapping("/detail/{mainId}")
//    public String detail(@PathVariable("mainId") Long mainId, ModelMap mmap) {
//        //获取股票代码和名称
//        StockMainBoard selectMainBoard = stockMainBoardService.selectStockMainBoardByMainId(mainId);
//        String stockCode = selectMainBoard.getStockCode();
//        StockMainBoardDfcfHotRelatedStock stockMainBoardDfcfHotRelatedStock = new StockMainBoardDfcfHotRelatedStock();
//        stockMainBoardDfcfHotRelatedStock.setStockCode(stockCode);
//        //根据股票代码查询相关股票
//        List<StockMainBoardDfcfHotRelatedStock> stockMainBoardDfcfHotRelatedStockList = stockMainBoardDfcfHotRelatedStockService.selectStockMainBoardDfcfHotRelatedStockList(stockMainBoardDfcfHotRelatedStock);
//
//        StockMainBoardDfcfHotRelatedStock stockMainBoardDfcfHotRelatedStock1 = new StockMainBoardDfcfHotRelatedStock();
//        Long dfcfHotId = 0L;
//        if (stockMainBoardDfcfHotRelatedStockList.size() != 0) {
//            stockMainBoardDfcfHotRelatedStock1 = stockMainBoardDfcfHotRelatedStockList.get(0);
//            dfcfHotId = stockMainBoardDfcfHotRelatedStock1.getDfcfHotId();
//        }
//
//        Object[] hotObject = new Object[3];
//        //相关股票
//        StockMainBoardDfcfHotDetail stockMainBoardDfcfHotDetail = new StockMainBoardDfcfHotDetail();
//        stockMainBoardDfcfHotDetail.setDfcfHotId(dfcfHotId);
//        //热点详细
//        List<StockMainBoardDfcfHotDetail> oneStockMainBoardDfcfHotDetailList = stockMainBoardDfcfHotDetailService.selectStockMainBoardDfcfHotDetailList(stockMainBoardDfcfHotDetail);
//        List<StockMainBoardDfcfHotDetail> twoStockMainBoardDfcfHotDetailList = oneStockMainBoardDfcfHotDetailList.stream().sorted(Comparator.comparing(StockMainBoardDfcfHotDetail::getDfcfHotDetailTime).reversed()).collect(Collectors.toList());
//
//        twoStockMainBoardDfcfHotDetailList.stream().max(Comparator.comparing(StockMainBoardDfcfHotDetail::getCreateTime));
//        //热点概念
//        StockMainBoardDfcfHot stockMainBoardDfcfHot = stockMainBoardDfcfHotService.selectStockMainBoardDfcfHotByDfcfHotId(dfcfHotId);
//        hotObject[0] = stockMainBoardDfcfHotRelatedStock1;
//        hotObject[1] = twoStockMainBoardDfcfHotDetailList;
//        hotObject[2] = stockMainBoardDfcfHot;
//
//        //主板股票
//        StockMainBoard stockMainBoardInsert = stockMainBoardService.selectStockMainBoardByMainId(mainId) == null ? new StockMainBoard() : stockMainBoardService.selectStockMainBoardByMainId(mainId);
//        //东方财富热点
//        StockMainBoardDfcfHot stockMainBoardDfcfHotInsert = (StockMainBoardDfcfHot) hotObject[2] == null ? new StockMainBoardDfcfHot() : (StockMainBoardDfcfHot) hotObject[2];
//        //东方财富热点详细对象
//        List<StockMainBoardDfcfHotDetail> stockMainBoardDfcfHotDetailList = (List<StockMainBoardDfcfHotDetail>) hotObject[1];
//        Optional<StockMainBoardDfcfHotDetail> maxOptionalStockMainBoardDfcfHotDetail = stockMainBoardDfcfHotDetailList.stream().max(Comparator.comparing(StockMainBoardDfcfHotDetail::getDfcfHotDetailTime));
//        StockMainBoardDfcfHotDetail stockMainBoardDfcfHotDetailInsert = maxOptionalStockMainBoardDfcfHotDetail.isEmpty() ? new StockMainBoardDfcfHotDetail() : maxOptionalStockMainBoardDfcfHotDetail.get();
//        //东方财富热点相关股票
//        StockMainBoardDfcfHotRelatedStock stockMainBoardDfcfHotRelatedStockInsert = (StockMainBoardDfcfHotRelatedStock) hotObject[0];
//
//        StockMainBoardGeneralMessage stockMainBoardGeneralMessage = new StockMainBoardGeneralMessage();
//        stockMainBoardGeneralMessage.setStockMainBoard(stockMainBoardInsert);
//        stockMainBoardGeneralMessage.setStockMainBoardDfcfHot(stockMainBoardDfcfHotInsert);
//        stockMainBoardGeneralMessage.setStockMainBoardDfcfHotDetail(stockMainBoardDfcfHotDetailInsert);
//        stockMainBoardGeneralMessage.setStockMainBoardDfcfHotRelatedStock(stockMainBoardDfcfHotRelatedStockInsert);
//
//        mmap.put("stockMainBoardGeneralMessage", stockMainBoardGeneralMessage);
//        return prefix + "/detail";
//    }

    /**
     * 删除股票主板
     */
    @Log(title = "股票主板", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        String[] idsSplit = ids.split(",");
        for (String id : idsSplit) {
            StockMainBoardDetail stockMainBoardDetail = new StockMainBoardDetail();
            stockMainBoardDetail.setMainId(Long.valueOf(id));
            List<StockMainBoardDetail> stockMainBoardDetails = stockMainBoardDetailService.selectStockMainBoardDetailList(stockMainBoardDetail);
            if (stockMainBoardDetails.size() > 0) {
                String joint = stockMainBoardDetails.stream()
                        .map(a -> {
                            Long detailId = a.getDetailId();
                            return String.valueOf(detailId);
                        }) // 提取name属性
                        .collect(Collectors.joining(","));
                stockMainBoardDetailService.deleteStockMainBoardDetailByDetailIds(joint);
            }
        }
        return toAjax(stockMainBoardService.deleteStockMainBoardByMainIds(ids));
    }


    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<StockMainBoard> util = new ExcelUtil<StockMainBoard>(StockMainBoard.class);
        return util.importTemplateExcel("股票主表数据");
    }

    /**
     * 主板股票数据导入
     */

    @Log(title = "股票主板", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<StockMainBoard> util = new ExcelUtil<StockMainBoard>(StockMainBoard.class);
        List<StockMainBoard> stockMainBoardList = util.importExcel(file.getInputStream());
        String message = stockMainBoardService.importStockMainBoard(stockMainBoardList, updateSupport, getLoginName());
        return AjaxResult.success(message);
    }

    /**
     * 改变购买状态
     */
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(StockMainBoard stockMainBoard) {
        return toAjax(stockMainBoardService.changeStatus(stockMainBoard));

    }


    /**
     * 将参数分成批次
     */
    private static List<List<String>> createBatches(List<String> list, int batchSize) {
        List<List<String>> batches = new ArrayList<>();
        for (int i = 0; i < list.size(); i += batchSize) {
            batches.add(list.subList(i, Math.min(i + batchSize, list.size())));
        }
        return batches;
    }


    /**
     * 查询股票创业板列表
     */

    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(StockMainBoard stockMainBoard) {
        //创业板类型
        stockMainBoard.setStockType("2");
        //设置流通市值的各种状态
        //设置流通市值的各种状态
        String actualCirculationStatus = stockMainBoard.getActualCirculationStatus();
        if (StringUtils.isNotEmpty(actualCirculationStatus)) {
            if (actualCirculationStatus.equals("0")) {
                stockMainBoard.setActualCirculationAllStatus("0");
            } else if (actualCirculationStatus.equals("1")) {
                stockMainBoard.setActualCirculationTypeStatus("1");
            } else if (actualCirculationStatus.equals("2")) {
                stockMainBoard.setActualCirculationTypeStatus("2");
            } else if (actualCirculationStatus.equals("3")) {
                stockMainBoard.setActualCirculationTypeStatus("3");
            }
        }

        //固定题材
        String fixTopicsStatus = stockMainBoard.getFixTopicsStatus();
        if (StringUtils.isNotEmpty(fixTopicsStatus)) {

            if (fixTopicsStatus.equals("1")) {

                stockMainBoard.setFixTopicsOne("1");

            } else if (fixTopicsStatus.equals("2")) {

                stockMainBoard.setFixTopicsTwo("2");

            } else if (fixTopicsStatus.equals("3")) {

                stockMainBoard.setFixTopicsThree("3");

            } else if (fixTopicsStatus.equals("4")) {

                stockMainBoard.setFixTopicsFour("4");

            } else if (fixTopicsStatus.equals("5")) {

                stockMainBoard.setFixTopicsFive("5");

            } else if (fixTopicsStatus.equals("6")) {

                stockMainBoard.setFixTopicsSix("6");

            } else if (fixTopicsStatus.equals("7")) {

                stockMainBoard.setFixTopicsSeven("7");

            } else if (fixTopicsStatus.equals("8")) {

                stockMainBoard.setFixTopicsEight("8");

            } else if (fixTopicsStatus.equals("9")) {

                stockMainBoard.setFixTopicsNine("9");

            } else if (fixTopicsStatus.equals("10")) {

                stockMainBoard.setFixTopicsTen("10");

            }
        }

        //龙头题材
        String dragonTopicsStatus = stockMainBoard.getDragonTopicsStatus();
        if (StringUtils.isNotEmpty(dragonTopicsStatus)) {

            if (dragonTopicsStatus.equals("1")) {

                stockMainBoard.setDragonTopicsOne("1");

            } else if (dragonTopicsStatus.equals("2")) {

                stockMainBoard.setDragonTopicsTwo("2");

            } else if (dragonTopicsStatus.equals("3")) {

                stockMainBoard.setDragonTopicsThree("3");

            } else if (dragonTopicsStatus.equals("4")) {

                stockMainBoard.setDragonTopicsFour("4");

            } else if (dragonTopicsStatus.equals("5")) {

                stockMainBoard.setDragonTopicsFive("5");

            } else if (dragonTopicsStatus.equals("6")) {

                stockMainBoard.setDragonTopicsSix("6");

            } else if (dragonTopicsStatus.equals("7")) {

                stockMainBoard.setDragonTopicsSeven("7");

            } else if (dragonTopicsStatus.equals("8")) {

                stockMainBoard.setDragonTopicsEight("8");

            } else if (dragonTopicsStatus.equals("9")) {

                stockMainBoard.setDragonTopicsNine("9");

            } else if (dragonTopicsStatus.equals("10")) {

                stockMainBoard.setDragonTopicsTen("10");

            }
        }

        stockMainBoard.setActualCirculationStatus("");
        stockMainBoard.setFixTopicsStatus("");
        stockMainBoard.setDynamicTopicsStatus("");
        stockMainBoard.setDragonTopicsStatus("");
        startPage();
        List<StockMainBoard> list = stockMainBoardService.selectStockMainBoardList(stockMainBoard);
        return getDataTable(list);
    }

    @Log(title = "股票主板细节表生成", businessType = BusinessType.GENCODE)
    @GetMapping("/batchStockMainBoardDetail")
    @ResponseBody
    public void batchStockMainBoardDetail(HttpServletResponse response) throws IOException {

    }





//    @PostMapping("/kplLhb/getData")
//    @ResponseBody
//    public List<Map<String, String>> getData(@Validated StockMainBoard stockMainBoard) {
//        Long mainId = stockMainBoard.getMainId();
//        StockMainBoardKplLhb stockMainBoardKplLhb = new StockMainBoardKplLhb();
//        stockMainBoardKplLhb.setMainId(mainId);
//        List<StockMainBoardKplLhb> stockMainBoardKplLhbsList = stockMainBoardKplLhbService.selectStockMainBoardKplLhbList(stockMainBoardKplLhb);
//
//
//        List<StockMainBoardKplLhb> stockMainBoardKplLhbsListReversed = stockMainBoardKplLhbsList.stream().sorted(Comparator.comparing(StockMainBoardKplLhb::getKplLhbTime).reversed()).collect(Collectors.toList());
//        List<Map<String, String>> data = new ArrayList<>();
//        String dateFormat = "yyyy-MM-dd";
//        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
//        for (int i = 0; i < stockMainBoardKplLhbsListReversed.size(); i++) {
//            //第一个
//            StockMainBoardKplLhb oneStockMainBoardKplLhb = stockMainBoardKplLhbsListReversed.get(i);
//            Date oneKplLhbTime = oneStockMainBoardKplLhb.getKplLhbTime();
//            String oneSetKplLhbTime = sdf.format(oneKplLhbTime);
//            //第二个
//            String twoSetKplLhbTime = "";
//            String twoKplLhbHotMoneyName = "";
//            if (stockMainBoardKplLhbsList.size() - 1 != i) {
//                StockMainBoardKplLhb twoStockMainBoardKplLhb = stockMainBoardKplLhbsListReversed.get(i + 1);
//                Date twoKplLhbTime = twoStockMainBoardKplLhb.getKplLhbTime();
//                twoSetKplLhbTime = sdf.format(twoKplLhbTime);
//
//            }
//
//
//            Map<String, String> row = new HashMap<>();
//
//            row.put("column1", oneSetKplLhbTime);
////            row.put("column2", oneKplLhbHotMoneyName);
//            row.put("column3", twoSetKplLhbTime);
//            row.put("column4", twoKplLhbHotMoneyName);
//            data.add(row);
//            i += 1; // 每次增加4个数据项
//        }
//        return data;
//    }

}
